package com.wlf.xxljob;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.google.common.collect.Lists;
import com.wlf.constant.Constants;
import com.wlf.entity.MqMessage;
import com.wlf.entity.User;
import com.wlf.mq.send.DirectMsgSender;
import com.wlf.service.IMqMessageService;
import com.wlf.service.IUserService;
import com.wlf.service.impl.RedisService;
import com.wlf.util.MqUtils;
import com.wlf.util.Pools;
import com.wlf.util.SnowflakeIdUtils;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Component
public class SelectUserJob {

    private static Logger logger = LoggerFactory.getLogger(SelectUserJob.class);
    @Autowired
    private IUserService userService;

    @Autowired
    private DirectMsgSender directMsgSender;

    @Autowired
    private RedisService redisService;

    @Autowired
    private IMqMessageService mqMessageService;

    @Value("${utruck.config.api.max-size}")
    private Integer maxSize;

    /**
     * 1、简单任务示例（Bean模式）
     */
    @XxlJob("userJobHandler")
    public ReturnT<String> userJobHandler(String param) throws Exception {
        try {
            String id = SnowflakeIdUtils.getId();
            String userName ="rabbitmq_"+id;
            String passWord ="password_"+id;
            int age =18;
            User user = this.getUser(id,age,userName,passWord);
            String msg = com.alibaba.fastjson.JSONObject.toJSONString(user);
            //存入redis
            redisService.set(id,msg);
            MqMessage mqMessage = this.getMqMessage(id,Constants.MESSAGETYPE_ORDER,id,msg,msg);
            mqMessageService.insert(mqMessage);
            //发送mq
            directMsgSender.sendPrint(msg, MqUtils.calcQueueIndex(maxSize,id));

            //发送邮件
          /* MailUtil mailUtil = new MailUtil();
          mailUtil.sendEmail(Constants.SENT_EMAIL_FROM_TO,msg);*/
        } catch (Exception e) {
            logger.info("执行失败：{}",e.getMessage());
            e.printStackTrace();
        }
        return ReturnT.SUCCESS;
    }


    /**
     * mq消费失败 定时任务重新发送
     */
    @XxlJob("mqResendJobHandler")
    public ReturnT<String> mqResendJobHandler(String param) throws Exception {
        try {

            MqMessage mqMessage = new MqMessage();
            mqMessage.setDeleted(Constants.ZERO);
            mqMessage.setIsCustomer(Constants.ZERO);

            List<MqMessage> list = mqMessageService.getMqMessageList(mqMessage);
            logger.info("mq重新消费开始，本次处理数量:{}",list.size());
            if(CollectionUtils.isNotEmpty(list)){
                List<List<MqMessage>> totalList = Lists.partition(list,20);
                totalList.stream().forEach(excuteList -> {
                    Pools.monitorExcute.execute(()->{
                        excuteList.stream().forEach(message->{
                            String msg = com.alibaba.fastjson.JSONObject.toJSONString(message);
                            //发送mq
                            directMsgSender.sendPrint(msg, MqUtils.calcQueueIndex(maxSize,message.getId()));
                        });
                    });
                });
            }
            logger.info("mq重新消费处理结束");
        } catch (Exception e) {
            logger.info("执行失败：{}",e.getMessage());
            e.printStackTrace();
            return ReturnT.FAIL;
        }
        return ReturnT.SUCCESS;
    }

    private  User getUser(String id,int age,String userName,String passWord){
        User user = new User();
        user.setId(id);
        user.setAge(age);
        user.setUsername(userName);
        user.setPassword(passWord);
        return user;
    }

    private MqMessage getMqMessage(String id,String messageType,String businessId,String messageBody,String extData){

        MqMessage mqMessage = new MqMessage();
        mqMessage.setId(id);
        mqMessage.setMessageId(UUID.randomUUID().toString());
        mqMessage.setCreatedTime(new Date());
        mqMessage.setCreatedBy(1);
        mqMessage.setUpdatedBy(1);
        mqMessage.setUpdatedTime(new Date());
        mqMessage.setMessageType(messageType);
        mqMessage.setBusinessId(businessId);
        mqMessage.setMessageBody(messageBody);
        mqMessage.setExtData(extData);
        mqMessage.setIsCustomer(Constants.ZERO);
        mqMessage.setDeleted(Constants.DELETED);

        return mqMessage;
    }
}
